import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from '@/store'
import Cookies from 'js-cookie'
import less from 'less'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import * as  filters from '@/filters'
import { hasBtnPermission, refreshPermissions } from '@/utils'
// import './assets/font/iconfont.css' // 引入字体图标库

Vue.use(less)
Vue.use(ElementUI)

// 全局组件
import globalComponents from '@/components/components/globalComponents'

Vue.config.productionTip = false

Vue.component('globalComponents', globalComponents)
// 注册filter
Object.keys(filters).forEach(key => {
	Vue.filter(key, filters[key])
})
Vue.prototype.hasPerm = hasBtnPermission

Vue.prototype.refreshPermissions = refreshPermissions

// 导航守卫
router.beforeEach((to, from, next) => {
	NProgress.start()
	let token = Cookies.get('token')
	if (!token) {
		if (to.name === 'login') {
			next()
		} else {
			next({ path: '/login' })
		}
	} else {
		if (to.name === 'login') {
			next({ path: '/' })
			NProgress.done()
		} else {
			if (store.state.routes.length === 0) {// 判断用户拉取完
				store.dispatch('getRouter').then(accessRoutes => {
					router.addRoutes(accessRoutes) //添加到路由
					next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
				})
			} else {
				next()
			}
		}
	}
})

router.afterEach(() => {
	NProgress.done()
})

new Vue({
	router,
	store,
	render: h => h(App)
}).$mount('#app')
